package com.icetec.iceintel.ui.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.HapticFeedbackConstants;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.icetec.R;
import com.icetec.iceintel.database.AlarmConfigSqlHelper;
import com.icetec.iceintel.framework.IceBaseActivity;
import com.icetec.iceintel.framework.ThreadExecutor;
import com.icetec.iceintel.model.Alarm;
import com.icetec.iceintel.netrequest.InstructionAccepter;
import com.icetec.iceintel.netrequest.InstructionAccepterCallback;
import com.icetec.iceintel.netrequest.InstrutionSender;
import com.icetec.iceintel.service.AlarmServiceBroadcastReciever;
import com.icetec.iceintel.ui.adapter.AlarmListAdapter;
import com.icetec.iceintel.ui.adapter.SleepAlarmAdapter;
import com.icetec.iceintel.utility.ToastUtility;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by amo on 2015/2/16.
 * 闹钟列表页面
 */
public class AlarmListActivity extends IceBaseActivity {

    ListView alarmListView;
    ListView sleepListView;
    AlarmListAdapter alarmListAdapter;
    SleepAlarmAdapter sleepAlarmAdapter;

    TextView backtv;
    TextView alarmClearTv;

    ImageView alarmAwakeTipsIV;
    ImageView alarmSleepTipsIV;

    Button addWakeAlarmBtn;
    Button sleepAlarmBtn;

    InstrutionSender instrutionSender;

    AlarmConfigSqlHelper alarmConfigSqlHelper;

    InstructionAccepter instructionAccepter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        instrutionSender=new InstrutionSender();



        setContentView(R.layout.activity_alarmlist);
        alarmListView=(ListView)findViewById(R.id.activity_alarmlist_listview);
        sleepListView=(ListView)findViewById(R.id.activity_alarmlist_listview_sleep);
        alarmClearTv=(TextView)findViewById(R.id.alarmlist_clearall_tv);
        alarmAwakeTipsIV=(ImageView)findViewById(R.id.alarm_awake_icon_detail_iv);
        alarmSleepTipsIV=(ImageView)findViewById(R.id.alarm_sleep_icon_detail_iv);


        alarmConfigSqlHelper=new AlarmConfigSqlHelper();
        alarmConfigSqlHelper.deleteActiveAlarm();

        alarmListAdapter=new AlarmListAdapter();
        alarmListView.setAdapter(alarmListAdapter);

        sleepAlarmAdapter=new SleepAlarmAdapter();
        sleepListView.setAdapter(sleepAlarmAdapter);




        backtv=(TextView)findViewById(R.id.alarmlist_back_tv);
        addWakeAlarmBtn=(Button)findViewById(R.id.alarm_list_addalarm_btn);
        sleepAlarmBtn=(Button)findViewById(R.id.alarm_list_addsleep_btn);



        alarmClearTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(AlarmListActivity.this).setMessage(R.string.ensure_delete_all_alarms).setPositiveButton(R.string.ensure,new DialogInterface.OnClickListener()
                {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //清空数据库数据
                       alarmConfigSqlHelper.deleteAllAlarm();

                        //刷新UI
                       alarmListAdapter.refreshData();
                       sleepAlarmAdapter.refreshData();

                        //发送清空指令
                        instrutionSender.clearAlarm();

                        callMathAlarmScheduleService();

                    }


                }).setNegativeButton(R.string.back, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {


                    }
                }).show();
            }
        });


        backtv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        addWakeAlarmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(alarmConfigSqlHelper.getAllAlarm(Alarm.AlarmType.AWAKE).size()<10){

                Intent newAlarmIntent = new Intent(AlarmListActivity.this, AlarmModificationActivity.class);
                newAlarmIntent.putExtra("type", Alarm.AlarmType.AWAKE);
                startActivity(newAlarmIntent);}

                else{

                    ToastUtility.show(R.string.too_more_alarm);


                }
            }
        });

        sleepAlarmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if(alarmConfigSqlHelper.getAllAlarm(Alarm.AlarmType.SLEEP).size()<10) {
                    Intent newAlarmIntent = new Intent(AlarmListActivity.this, AlarmModificationActivity.class);
                    newAlarmIntent.putExtra("type", Alarm.AlarmType.SLEEP);
                    startActivity(newAlarmIntent);
                }

                else{

                    ToastUtility.show(R.string.too_more_alarm);

                }

            }
        });

        alarmAwakeTipsIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(AlarmListActivity.this)
                        .setTitle(R.string.alarm_awake)
                        .setIcon(R.drawable.lightadaptation_icon)
                        .setPositiveButton(R.string.i_know,null)
                        .setMessage(R.string.alarm_awake_explanation).show();
            }
        });

        alarmSleepTipsIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(AlarmListActivity.this)
                        .setTitle(R.string.alarm_sleep)
                        .setIcon(R.drawable.lightadaptation_icon)
                        .setPositiveButton(R.string.i_know,null)
                        .setMessage(R.string.alarm_sleep_explanation).show();
            }
        });


       alarmListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

           @Override
           public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
               v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
               Alarm alarm = (Alarm) alarmListAdapter.getItem(position);
               Intent intent = new Intent(AlarmListActivity.this, AlarmModificationActivity.class);
               intent.putExtra("alarm", alarm);
               startActivity(intent);
           }

       });

        sleepListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
                v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
                Alarm alarm = (Alarm) sleepAlarmAdapter.getItem(position);
                Intent intent = new Intent(AlarmListActivity.this, AlarmModificationActivity.class);
                intent.putExtra("alarm", alarm);
                startActivity(intent);
            }

        });

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setIcon(R.drawable.alram_set_icon);
        progressDialog.setMessage(getResources().getString(R.string.sync_alarms));
        progressDialog.setCancelable(false);


        new Handler().postDelayed(new Runnable(){
            public void run() {
            //    instrutionSender.queryAllDevices();
              instrutionSender.queryAlarm();

            }
        }, 3000);

        new Handler().postDelayed(new Runnable(){
            public void run() {
               progressDialog.dismiss();
            }
        }, 5000);

        instructionAccepter=new InstructionAccepter();
        instructionAccepter.setCallback(new InstructionAccepterCallback() {
            @Override
            public void onStart() {
                progressDialog.show();



            }

            @Override
            public void onReceivedUDPCreated() {


            }

            @Override
            public void getDeviceBeSave(Object device) {

                Log.i("闹钟查询回调", "储存成功");
                //这里不能用toast

                progressDialog.dismiss();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        alarmListAdapter.refreshData();
                        sleepAlarmAdapter.refreshData();

                    }
                });

                callMathAlarmScheduleService();


            }

            @Override
            public void onPost(Boolean result) {
                //     ToastUtility.show("数据同步通道已关闭");
                //   callMathAlarmScheduleService();
                //     alarmListAdapter.refreshData();
                //    sleepAlarmAdapter.refreshData();
            }


        });
      instructionAccepter.executeOnExecutor(ThreadExecutor.executorService,100);


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
    //    MenuInflater inflater = getMenuInflater();
     //   inflater.inflate(R.menu.menu_alarm, menu);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public void onResume() {
        super.onResume();
        alarmListAdapter.refreshData();
        sleepAlarmAdapter.refreshData();

    }

    @Override
    protected void onDestroy() {
        instructionAccepter.interrrupt();
        super.onDestroy();
    }

    /*



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        String url = null;
        Intent intent = null;
        switch (item.getItemId()) {
            case R.id.menu_item_new:
                Intent newAlarmIntent = new Intent(this, AlarmModificationActivity.class);
                startActivity(newAlarmIntent);
                break;
            case R.id.menu_item_rate:
                url = "market://details?id=" + getPackageName();
                intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                try {
                    startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    Toast.makeText(this, "Couldn't launch the market", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.menu_item_website:
                url = "http://www.neilson.co.za";
                intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                try {
                    startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    Toast.makeText(this, "Couldn't launch the website", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.menu_item_report:

                url = "https://github.com/SheldonNeilson/Android-Alarm-Clock/issues";
                intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                try {
                    startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    Toast.makeText(this, "Couldn't launch the bug reporting website", Toast.LENGTH_LONG).show();
                }


			Intent send = new Intent(Intent.ACTION_SENDTO);
			String uriText;

			String emailAddress = "dontusemyemailaddress@yourdomain.com";
			String subject = R.string.app_name + " Bug Report";
			String body = "Debug:";
			body += "\n OS Version: " + System.getProperty("os.version") + "(" + android.os.Build.VERSION.INCREMENTAL + ")";
			body += "\n OS API Level: " + android.os.Build.VERSION.SDK_INT;
			body += "\n Device: " + android.os.Build.DEVICE;
			body += "\n Model (and Product): " + android.os.Build.MODEL + " (" + android.os.Build.PRODUCT + ")";
			body += "\n Screen Width: " + getWindow().getWindowManager().getDefaultDisplay().getWidth();
			body += "\n Screen Height: " + getWindow().getWindowManager().getDefaultDisplay().getHeight();
			body += "\n Hardware Keyboard Present: " + (getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS);

			uriText = "mailto:" + emailAddress + "?subject=" + subject + "&body=" + body;

			uriText = uriText.replace(" ", "%20");
			Uri emalUri = Uri.parse(uriText);

			send.setData(emalUri);
			startActivity(Intent.createChooser(send, "Send mail..."));

                break;
        }
        return super.onOptionsItemSelected(item);
    }

    */

    protected void callMathAlarmScheduleService() {

        Log.i("启动服务","正在启动闹钟服务接收器");
        Intent mathAlarmServiceIntent = new Intent(this, AlarmServiceBroadcastReciever.class);
        sendBroadcast(mathAlarmServiceIntent, null);

    }






}
